﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Configuration;
using System.Data.SqlClient;
using System.Diagnostics;

namespace BizTalkOneService
{
    class EsbExceptionDb
    {
        List<Counter> counterList = new List<Counter>();
        EventLog appLog = new EventLog();
       
        public EsbExceptionDb()
        {
            
            try
            {
                string connectionString = ConfigurationManager.ConnectionStrings["EsbConnectionString"].ConnectionString;
                using (SqlConnection connection = new SqlConnection(connectionString))
                {
                    SqlCommand command = new SqlCommand(
                    "use EsbExceptionDb select [Application], count(*) as [Count] from fault with (nolock) group by application order by 1", connection);
                    connection.Open();

                    SqlDataReader dataReader = command.ExecuteReader();
                    if (dataReader.HasRows)
                    {
                        while (dataReader.Read())
                        {
                            counterList.Add(new Counter { CounterCategory = "EsbException", CounterName = dataReader.GetString(0),  CounterValue = dataReader.GetInt32(1) });
                        }
                    }
                    dataReader.Close();
                }
            }
            catch (Exception ex)
            {
                appLog.Source = Settings.EventLogSource;
                EventLogEntryType eventType = EventLogEntryType.Error;
                appLog.WriteEntry("Error retrieving Esb Exceptions: " + ex.Message.ToString() + "\n" + ex.StackTrace, eventType);
                this.counterList.Clear();
                this.counterList.Add(new Counter() { CounterCategory = "EsbException", CounterName = "Error", CounterValueString = String.Format("Error retrieving Esb Exceptions: " + ex.Message.ToString() + "\n" + ex.StackTrace) });
            }
        }

        public List<Counter> GetAppList()
        {
            return this.counterList;
        }
    }
}
